package meijuli.com.join51.business.ui.widget;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import meijuli.com.join51.business.R;
import meijuli.com.join51.business.activity.RechargeActivity;
import meijuli.com.join51.business.fragment.BaseFragment;
import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import com.jhx.common.model.EventBean;
import meijuli.com.join51.business.model.PayResult;
import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.utils.QREncoder;
import com.jhx.common.utils.ToastUtil;
import meijuli.com.join51.business.model.PayType;
import org.greenrobot.eventbus.EventBus;
import cn.iwgang.countdownview.CountdownView;
import retrofit2.Call;

/**
 *
 * Created by Administrator on 2017/3/3.
 */

public class QrPayFragment extends BaseFragment implements View.OnClickListener {

    private static final String PAY_RESULT = "code_url";
    private static final String PAY_TYPE = "pay_type";
    private static final long REQUEST_INTERVAL = 3000;
    private static final String URL_SHARE = "http://pan.baidu.com/share/qrcode?w=230&h=230&url=";

    TextView mHintText;
    ImageView mScanIv;
    ImageView mScanIvLogo;
    RelativeLayout mLlScanView;
    TextView mPaySurplusTime;
    CountdownView mScanCountdownView;
    TextView mPayText;
    TextView mShareBtn;
    ProgressBar mCheckPayProgress;

    private PayResult mPayResult;
    private String titleStr;
    private int icon;
    private Handler delayHandler = new Handler();
    private int questCnt = 0;

    public static QrPayFragment newInstance(PayResult payResult, int payType) {

        Bundle args = new Bundle();
        args.putSerializable(PAY_RESULT, payResult);
        args.putInt(PAY_TYPE, payType);
        QrPayFragment fragment = new QrPayFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mHintText = view.findViewById(R.id.hint_text);
        mScanIv = view.findViewById(R.id.scan_iv);
        mScanIvLogo = view.findViewById(R.id.scan_iv_logo);
        mLlScanView = view.findViewById(R.id.ll_scan_view);
        mPaySurplusTime = view.findViewById(R.id.pay_surplus_time);
        mScanCountdownView = view.findViewById(R.id.scan_countdown_view);
        mPayText = view.findViewById(R.id.pay_text);
        mShareBtn = view.findViewById(R.id.share_btn);
        mCheckPayProgress = view.findViewById(R.id.check_pay_progress);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPayResult = (PayResult) getArguments().getSerializable(PAY_RESULT);
        int payType = getArguments().getInt(PAY_TYPE);
        if (payType == PayType.TYPE_ALI_PAY_SCAN) {
            titleStr = "支付宝";
            icon = R.mipmap.alipay;
        } else if (payType == PayType.TYPE_QQ_PAY) {
            titleStr = "QQ钱包";
            icon = R.mipmap.qq_icon;
        } else {
            titleStr = "微信";
            icon = R.mipmap.we_chat;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_scan, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mScanCountdownView.setVisibility(View.VISIBLE);
        mScanCountdownView.start(1000 * 60 * 5);
        mScanCountdownView.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
            @Override
            public void onEnd(CountdownView cv) {
                ToastUtil.getInstance().showToast(getActivity(), "二维码已失效");
            }
        });

        mPayText.setOnClickListener(this);
        mShareBtn.setOnClickListener(this);
        mScanIv.setOnClickListener(this);

        QREncoder.generateQRCodeImage(mPayResult.getCodeUrl(), mScanIv, 200, 0xFF30ABEF);

        setHintText(titleStr);
        setScanLogoIv(icon);

        ((RechargeActivity) mActivity).setToolBarTitle(titleStr + "扫码支付");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            ((RechargeActivity) mActivity).setToolBarTitle(titleStr + "扫码支付");
        }
    }

    public void setHintText(String text) {
        mHintText.setText(String.format("请打开%s，扫描二维码进行支付", text));
    }

    public void setScanLogoIv(@DrawableRes int scanLogoIv) {
        this.mScanIvLogo.setBackgroundResource(scanLogoIv);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.pay_text:
                mCheckPayProgress.setVisibility(View.VISIBLE);
                mCheckPayProgress.setProgress(1);
                setBtnClickable(false);
                startRequest();
                break;
            case R.id.share_btn:
                shareQR();
                break;
            default:

                break;
        }
    }

    private void setBtnClickable(boolean isClickable) {
        if (isClickable) {
            mPayText.setText("支付查询");
        } else {
            mPayText.setText("支付查询中...");
        }
        mPayText.setClickable(isClickable);
    }

    private void checkPayRequest() {
        delayHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mCheckPayProgress.setProgress(questCnt * 3);
                startRequest();
            }
        }, REQUEST_INTERVAL);
    }

    private void startRequest() {
        Call<HttpResponse<String>> call = ApiManager.get().getApiService(ApiService.class).checkPayment(mPayResult.getBustId());
        HttpRequest.getRequest().autoRecycle(getActivity()).start(call, false,
                new ResponseCallback<String>() {
                    @Override
                    public void onSuccess(String url, String data) {
                        questCnt = 0;
                        mCheckPayProgress.setProgress(9);
                        dismissDialog();
                        setBtnClickable(true);
                        showPaySuccessDialog();
                        EventBus.getDefault().post(new EventBean(EventBean.STATUS_UPDATE_MAIN));
                    }

                    @Override
                    public void onError(String url, int errorCode, String errorMsg) {
                        if (errorCode == HttpResponse.CODE_NOT_PAY) {
                            if (questCnt >= 3) {
                                ToastUtil.getInstance().showToast(mActivity, "支付失败");
                                dismissDialog();
                                setBtnClickable(true);
                            } else {
                                questCnt++;
                                checkPayRequest();
                            }
                        } else {
                            questCnt = 0;
                            mCheckPayProgress.setProgress(9);
                            ToastUtil.getInstance().showToast(errorMsg);
                            dismissDialog();
                            setBtnClickable(true);
                        }
                    }
                });
    }

    private void showPaySuccessDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        builder.setTitle("支付结果").setMessage("您已支付成功!").setPositiveButton("好的", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mHintText.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mActivity.finish();
                    }
                }, 200);
            }
        });
        builder.show();
    }

    private void shareQR() {
//        User user = UserManager.get().getUser();
//        UMWeb umWeb = ShareUtils.getUMWeb(getContext(), mPayResult.getCodeUrl(), user.getHeadImage(),
//                "来自 + " + user.getBusinessName() + "的分享", "");
//        ShareUtils.showShareDialog(getActivity(), umWeb);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mScanCountdownView != null) {
            mScanCountdownView.stop();
        }
    }
}
